import React, { Component } from 'react';
// import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import Loading from '../../components/Loading';
import SearchHeader from './Header';
import List from '../Home/Love/List';
import { fetchSearchResult } from '../../api/search.js';

const START_PAGE = 1;

class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: START_PAGE,
      hasMore: true,
      data: null,
      isFetching: true,
    }
  }

  handleBack = () => {
    this.props.history.push('/home');
  }
  handlePullDown = () => {
    const {page} = this.state;
    const {match} = this.props;
    const {type, keyword} = match.params;
    fetchSearchResult({
      page,
      type,
      keyword
    }).then(data => {
      this.setState({
        data,
        page: page + 1,
        isFetching: false,
        hasMore: data.total > page
      })
    })

  }
  handleSearch = (keyword) => {
    const {match, history} = this.props;
    // 只需要修改搜索词
    history.push(`/search/${START_PAGE}/${match.params.type}/${keyword}`);
  }

  componentDidMount() {
    const {history, match} = this.props;
    const {type} = match;
    if(!type) {
      history.push(`/search/${START_PAGE}/all/`);
    }
    // todo 绑定下拉刷新事件
    // 记录type和keyword到state
    // 处理请求结果
    this.handlePullDown();
  }

  render() {
    const {isFetching, data, hasMore} = this.state;
    if(isFetching) {
      return <Loading/>
    }
    return (
      <div className="search">
        <SearchHeader onClickIcon={this.handleBack} onSearch={this.handleSearch}/>
        <List data={data}/>
        {
          isFetching ? <Loading/> : <footer onClick={this.handlePullDown}>{hasMore ? '加载更多' : '没有更多内容了'}</footer>
        }
      </div>
    )
  }
}

export default withRouter(Search);
